package com.jbit.config;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jbit.pojo.MailLog;
import com.jbit.pojo.constant.MailConstant;
import com.jbit.service.IMailLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @program: yeb
 * @description: RabbitMQ配置类
 * @author: Mr.Li
 * @create: 2021-12-12 15:24
 **/
@Configuration
public class RabbitMQConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQConfig.class);

    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;
    @Autowired
    private IMailLogService mailLogService;

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        /**
         * 消息确认回调，确认消息是否到达broker
         * data：唯一标识 之前用UUID生成的
         * ack：是否确认
         * cause：失败的原因
         */
        rabbitTemplate.setConfirmCallback((data, ack, cause) -> {
            String id = data.getId();
            if (ack) {
                LOGGER.info("{}=======>消息发送成功", id);
                mailLogService.update(new UpdateWrapper<MailLog>().set("status", 1).eq("msgId", id));
            } else {
                LOGGER.info("{}=======>消息发送失败", id);
            }
        });
        /**
         * 消息失败回调
         * 比如router不到queue的时候就会回调
         * ReplyCode：响应码
         * ReplyText：响应描述
         */
            rabbitTemplate.setReturnsCallback(returnCallback -> {
            LOGGER.info("{}=======>消息发送queue时失败", returnCallback.getMessage().getBody());
        });
        return rabbitTemplate;
    }

    @Bean
    public Queue queue() {
        return new Queue(MailConstant.MAIL_QUEUE_NAME);
    }

    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange(MailConstant.MAIL_EXCHANGE_NAME);
    }

    @Bean
    public Binding binding() {
        return BindingBuilder.bind(queue()).to(directExchange()).with(MailConstant.MAIL_ROUTING_KEY_NAME);
    }
}
